-- ====================================
-- Initialize the timestep.
-- ====================================
local previousTime = nil
local elapsed = 0

-- ====================================
-- Methods
-- ====================================
-- Update the current timeline if need be.
function Orunj:UpdateTimeline()
	local timestep = self.settings.timestep
	
	-- Get the time in seconds since the computer booted up.
	-- [http://www.wowwiki.com/API_GetTime]
	now = GetTime()
	previousTime = previousTime or now
	elapsed = elapsed + (now - previousTime)
		
	-- If the elapsed time is greater than the timestep, then
	-- update the timeline for all players.
	if elapsed > timestep then
		self:UpdatePlayerTimelines(self.session.sequenceNumber)
		-- Only update the sequence number here.
		self.session.sequenceNumber = self.session.sequenceNumber + 1
		elapsed = 0
	end
	previousTime = now
end

-- Update the timeline state of each player.
function Orunj:UpdatePlayerTimelines(sequenceNumber)
	-- Get the list of players
	local players = self.session.players
	-- For each player, update his/her timeline.
	for k in pairs(players) do
		local player = players[k]
		local unitId = player.unitId
		-- make an entry for the current time.
		player.timelines.unitHealthTimeline[sequenceNumber] = UnitHealth(unitId)
		--player.timelines.unitHealthTimeline[sequenceNumber] = UnitHealthMax(unitId)
		player.timelines.unitPowerTimeline[sequenceNumber] = UnitPower(unitId)
		--player.timelines.unitPowerMaxTimeline[sequenceNumber] = UnitPowerMax(unitId)
		local x,y = GetPlayerMapPosition(unitId)
		player.timelines.xPositionTimeline[sequenceNumber] = x
		player.timelines.yPositionTimeline[sequenceNumber] = y
	end
end

-- Check to see if we need to update the map position info, based
-- on if the player's coordinates are (0,0). If they are, it is *very* likely
-- that the current map is wrong, and needs to be updated to reflect
-- the current player's position.
function Orunj:CheckForceMapUpdate()
	local x,y = GetPlayerMapPosition("player")
	if x == 0 and y == 0 then
		self:UpdateGlobalTimelineMap()
	end
end

-- Update the session's global timeline with a zone change event
function Orunj:UpdateGlobalTimelineMap()
	local sequenceNumber = self.session.sequenceNumber
	local mapTimeline = self.session.globalTimelines.mapTimeline
	
	-- Force the client to set the map to the currently visited map.
	SetMapToCurrentZone()
	
	-- Code here taken from HudMap.lua, at line 1859.
	local area, level, key
	area = GetMapInfo()
	level = GetCurrentMapDungeonLevel()
	if area == "Ulduar" or area == "CoTStratholme" then
		level = level - 1
	end
	key = level > 0 and (area .. level) or area
	local currentZone = self.zoneOverrides[GetSubZoneText()] or key
	
	-- Update the global timeline.
	mapTimeline[sequenceNumber] = currentZone
end